package com.geeklan.smart.ui.web;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.databinding.ActivityWebViewBinding;

public class WebViewActivity extends BaseActivity<ActivityWebViewBinding> {
    private String url;
    private String title;

    @Override
    protected ActivityWebViewBinding initBinding() {
        return ActivityWebViewBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(v -> {
            finish();
        });
        if(title != null){
            mBinding.tvTitle.setText(title);
        }
        WebSettings webSettings = mBinding.webview.getSettings();
        webSettings.setJavaScriptEnabled(true); // 启用JavaScript
        webSettings.setLoadWithOverviewMode(true); // 将图片调整到适合webview的大小
        webSettings.setUseWideViewPort(true); // 将图片扩展至整个屏幕的大小
        webSettings.setBuiltInZoomControls(true); // 支持缩放，即双击缩放
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setLoadsImagesAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mBinding.webview.clearCache(true);
        mBinding.webview.clearHistory();
        // 设置 WebViewClient 防止跳转到系统浏览器
        mBinding.webview.setWebViewClient(new WebViewClient());

        mBinding.webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                // 获取网页标题
                if(WebViewActivity.this.title == null){
                    mBinding.tvTitle.setText(title);
                }
            }
        });
        // 加载网页
        mBinding.webview.setWebViewClient(new MyWebViewClient());
        if(url.startsWith("http")) {
            mBinding.webview.loadUrl(url);
        }else {
            mBinding.webview.loadDataWithBaseURL(null, url, "text/html", "utf-8", null);
        }
    }

    class MyWebViewClient extends WebViewClient{
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
            super.onReceivedSslError(view, handler, error);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }
    }

    @Override
    protected void onDestroy() {
        mBinding.webview.destroy();
        super.onDestroy();
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, String url,String title) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }
}